package controllers;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import models.Library;
import models.Player;
import models.UpdateResponse;
import play.mvc.Controller;
import play.mvc.Http.Response;
import play.mvc.Result;
import utils.XMLUtil;

public class Application extends Controller {
	private static final String BASE_PATH = "/home/energy/java_lib/";

	/**
	 * 
	 * 文件下载
	 * 
	 * @param name
	 *            文件名
	 * @return
	 */
	public static Result download(String name) {
		String pathName = BASE_PATH + name;
		File file = new File(pathName);
		Response response = response();
		response.setHeader("Content-Disposition", "attachment; filename=" + name);
		return ok(file);
	}

	/**
	 * 获取更新数据
	 * 
	 * @return xml
	 */
	public static Result getUpdateXml() {
		UpdateResponse response = init();
		String content = XMLUtil.toXML(response);
		response().setHeader("Content-type", "text/xml");
		response().setHeader("charsete", "utf-8");
		return ok(content);

	}

	/**
	 * 获取更新数据
	 * 
	 * @return json
	 */
	public static Result getUpdateJson() {
		UpdateResponse response = init();
		String content = XMLUtil.toJson(response);
		response().setHeader("charsete", "utf-8");
		return ok(content);
	}

	public static UpdateResponse init() {
		UpdateResponse response = new UpdateResponse();
		response.setPlayer(new Player("2.2.1", "monstarch.air"));
		List<Library> librarys = new ArrayList<Library>();
		File path = new File(BASE_PATH);
		File[] files = path.listFiles();
		for (File file : files) {
			if (file.isFile()) {
				librarys.add(new Library(file.getName()));
			}
		}
		response.setLibrarys(librarys);
		return response;
	}
}